/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */
 
package edu.tju.commons.text;

/**
 * Utility methods for encoding and decoding values in various encoding formats.
 */
public class EncodingUtil {

	/**
	 * Translates a binary value (in the form of a byte array) to its
	 * hexadecimal value. Each byte is translated to a two-digit hexadecimal
	 * value, e.g. the byte value <tt>10</tt> is translated to <tt>0A</tt>.
	 *
	 * @param bytes
	 *        The binary value to translate to hexadecimal.
	 * @return The hexadecimal value of the binary input.
	 */
	public static String binary2hex(byte[] bytes) {
		StringBuilder hexString = new StringBuilder(bytes.length * 2);

		for (int i = 0; i < bytes.length; i++) {
			int b = (int) bytes[i];

			// Make sure b is a positive number
			if (b < 0) {
				b += 256;
			}

			String hexValue = Integer.toHexString(b).toUpperCase();

			// Make sure two characters are used for 'hexValue'
			if (hexValue.length() == 1) {
				hexString.append('0');
			}

			hexString.append(hexValue);
		}

		return hexString.toString();
	}

	/**
	 * Translates an hexadecimal value to binary (in the form of a byte array).
	 * Every two hexadecimal digits are translated to a single byte, e.g. the
	 * hexadecimal value <tt>0A</tt> is translated to a single byte with the
	 * value <tt>10</tt>.
	 *
	 * @param hexString
	 *        The hexadecimal value to translate to binary.
	 * @return The binary value to the hexadecimal input.
	 * @exception NumberFormatException
	 *            If the supplied <tt>hexString</tt> does not represent an
	 *            hexadecimal value.
	 */
	public static byte[] hex2binary(String hexString) {
		// prepend a zero to hexString if it contains an odd number of
		// characters
		if (hexString.length() % 2 != 0) {
			hexString = "0" + hexString;
		}

		byte[] bytes = new byte[hexString.length() / 2];

		for (int i = 0; i < bytes.length; i++) {
			String hexValue = hexString.substring(2 * i, 2 * i + 2);
			int b = Integer.parseInt(hexValue, 16);
			bytes[i] = (byte) b;
		}

		return bytes;
	}
}
